﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Xml.Serialization;

// 订单明细类
[Serializable]
public class OrderDetails
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }

    public override bool Equals(object obj)
    {
        return obj is OrderDetails details &&
               Id == details.Id &&
               ProductName == details.ProductName &&
               Quantity == details.Quantity &&
               Price == details.Price;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + Id.GetHashCode();
            hash = hash * 23 + (ProductName?.GetHashCode() ?? 0);
            hash = hash * 23 + Quantity.GetHashCode();
            hash = hash * 23 + Price.GetHashCode();
            return hash;
        }
    }

    public override string ToString()
    {
        return $"明细ID: {Id}, 商品名称: {ProductName}, 数量: {Quantity}, 单价: {Price}";
    }
}

// 订单类
[Serializable]
public class Order
{
    public Order() { } // 添加无参构造函数
    public int OrderId { get; set; }
    public string Customer { get; set; }
    public List<OrderDetails> OrderDetails { get; set; }
    public double TotalAmount => OrderDetails.Sum(d => d.Quantity * d.Price);

    public override bool Equals(object obj)
    {
        return obj is Order order &&
               OrderId == order.OrderId;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            hash = hash * 23 + OrderId.GetHashCode();
            hash = hash * 23 + (Customer?.GetHashCode() ?? 0);
            // 考虑订单明细的哈希值，遍历所有明细计算
            foreach (var detail in OrderDetails ?? Enumerable.Empty<OrderDetails>())
            {
                hash = hash * 23 + detail.GetHashCode();
            }
            return hash;
        }
    }

    public override string ToString()
    {
        string details = string.Join("\n  ", OrderDetails.Select(d => d.ToString()));
        return $"订单号: {OrderId}, 客户: {Customer}, 总金额: {TotalAmount}\n  {details}";
    }
}

// 订单服务类
public class OrderService
{
    private List<Order> orders = new List<Order>();

    public void AddOrder(Order order)
    {
        if (orders.Contains(order))
        {
            throw new ArgumentException($"订单号 {order.OrderId} 已存在，不能重复添加。");
        }
        orders.Add(order);
    }

    public void DeleteOrder(int orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new ArgumentException($"订单号 {orderId} 不存在，删除失败。");
        }
        orders.Remove(order);
    }

    public void UpdateOrder(Order updatedOrder)
    {
        var index = orders.FindIndex(o => o.OrderId == updatedOrder.OrderId);
        if (index == -1)
        {
            throw new ArgumentException($"订单号 {updatedOrder.OrderId} 不存在，修改失败。");
        }
        orders[index] = updatedOrder;
    }

    public List<Order> QueryOrdersByOrderId(int orderId)
    {
        return orders.Where(o => o.OrderId == orderId).OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByProductName(string productName)
    {
        return orders.Where(o => o.OrderDetails.Any(d => d.ProductName == productName))
                     .OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByCustomer(string customer)
    {
        return orders.Where(o => o.Customer == customer).OrderBy(o => o.TotalAmount).ToList();
    }

    public List<Order> QueryOrdersByTotalAmount(double minAmount, double maxAmount)
    {
        return orders.Where(o => o.TotalAmount >= minAmount && o.TotalAmount <= maxAmount)
                     .OrderBy(o => o.TotalAmount).ToList();
    }

    public void SortOrders()
    {
        orders = orders.OrderBy(o => o.OrderId).ToList();
    }

    public void SortOrders(Func<Order, Order, int> comparison)
    {
        orders.Sort((x, y) => comparison(x, y));
    }

    public void DisplayOrders()
    {
        foreach (var order in orders)
        {
            Console.WriteLine(order);
            Console.WriteLine();
        }
    }

    public void Export(string filePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        {
            serializer.Serialize(fs, orders);
        }
    }

    public void Import(string filePath)
    {
        if (!File.Exists(filePath))
            throw new FileNotFoundException("XML文件不存在");

        XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
        using (FileStream fs = new FileStream(filePath, FileMode.Open))
        {
            List<Order> imported = (List<Order>)serializer.Deserialize(fs);
            orders = imported; // 替换现有订单
        }
    }
}

class Program
{
    static void Main()
    {
        OrderService orderService = new OrderService();

        try
        {
            // 添加订单
            Order order1 = new Order
            {
                OrderId = 1,
                Customer = "张三",
                OrderDetails = new List<OrderDetails>
                {
                    new OrderDetails { Id = 1, ProductName = "手机", Quantity = 2, Price = 5000 },
                    new OrderDetails { Id = 2, ProductName = "电脑", Quantity = 1, Price = 8000 }
                }
            };
            orderService.AddOrder(order1);

            Order order2 = new Order
            {
                OrderId = 2,
                Customer = "李四",
                OrderDetails = new List<OrderDetails>
                {
                    new OrderDetails { Id = 3, ProductName = "相机", Quantity = 1, Price = 6000 },
                    new OrderDetails { Id = 4, ProductName = "打印机", Quantity = 1, Price = 2000 }
                }
            };
            orderService.AddOrder(order2);

            // 显示所有订单
            Console.WriteLine("所有订单信息：");
            orderService.DisplayOrders();

            // 查询订单
            Console.WriteLine("按订单号查询订单号为1的订单：");
            var queryResult1 = orderService.QueryOrdersByOrderId(1);
            foreach (var order in queryResult1)
            {
                Console.WriteLine(order);
            }

            // 修改订单
            order1.OrderDetails.Add(new OrderDetails { Id = 5, ProductName = "耳机", Quantity = 1, Price = 500 });
            orderService.UpdateOrder(order1);
            Console.WriteLine("修改后的订单信息：");
            orderService.DisplayOrders();

            // 删除订单
            orderService.DeleteOrder(2);
            Console.WriteLine("删除订单号为2的订单后，剩余订单信息：");
            orderService.DisplayOrders();

            // 排序订单
            orderService.SortOrders();
            Console.WriteLine("按订单号排序后的订单信息：");
            orderService.DisplayOrders();

            // 自定义排序
            orderService.SortOrders((x, y) => x.TotalAmount.CompareTo(y.TotalAmount));
            Console.WriteLine("按订单总金额排序后的订单信息：");
            orderService.DisplayOrders();
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine($"操作出错: {ex.Message}");
        }
    }
}